package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Transactional
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    private String prefix; //素材在阿里云OSS上的顶层目录

    @Value("${file.oss.web-site}")
    private String webSite; //访问阿里云OSS素材的域名


    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1.判断参数是否合法
        if(multipartFile==null || multipartFile.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.自定义唯一文件名
        String prefixPathName = UUID.randomUUID().toString().replace("-",""); //定义文件名前缀，保证文件名唯一

        //假设源文件名为11.22.33.png
        String originalFilename = multipartFile.getOriginalFilename();//原始文件名
        int lastIndex = originalFilename.lastIndexOf(".");//获取最后一个.的索引位置
        String postfixPathName = originalFilename.substring(lastIndex); //获取原始文件后缀名

        //拼接新的文件名
        String finalFileName = prefixPathName + postfixPathName;

        //4.调用OSS执行上传获取上传后的文件相对路径
        String filePath = "";
        try {
            filePath = fileStorageService.store(prefix, finalFileName, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "上传失败");
        }

        //5.将素材信息条件到表中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(wmUser.getId()); //自媒体用户ID
        wmMaterial.setIsCollection((short)0); //0-未收藏  1-已收藏
        wmMaterial.setUrl(filePath); //素材在OSS上的相对路径
        wmMaterial.setType((short)0); //0-图片  1-视频
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //6.将域名拼接到素材路径之前，用于回显到页面
        wmMaterial.setUrl(webSite + wmMaterial.getUrl());


        WmThreadLocalUtils.clear(); //清理当前线程绑定的用户数据
        //7.响应数据
        return ResponseResult.okResult(wmMaterial);
    }


    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.判断参数是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        //2.判断是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.判断dto里isCollection如果大于0则拼接查询条件
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(dto.getIsCollection()>0){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        //设置固定查询条件-当前登录用户ID
        lambdaQueryWrapper.eq(WmMaterial::getUserId, wmUser.getId());
        //所有素材按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //4.执行分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page,lambdaQueryWrapper);

        //5.响应结果的每一条素材都要在路径上拼接域名
        page.getRecords().forEach(x->{
            x.setUrl(webSite + x.getUrl());
        });

        //6.封装分页响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        WmThreadLocalUtils.clear(); //清理当前线程绑定的用户数据
        //7.响应数据
        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult del(Integer id) {
        //1.判断参数合法性
        if(id==null || id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.根据ID查询素材是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材不存在");
        }

        //4.判断素材是否被文章引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "素材被引用不能删除");
        }

        //5.根据ID从素材表删除
        removeById(id);

        //6.删除OSS中的素材
        fileStorageService.delete(wmMaterial.getUrl());

        WmThreadLocalUtils.clear(); //清理当前线程绑定的用户数据

        //7.响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Override
    public ResponseResult collect(Integer id, Short isCollection) {
        //1.判断参数合法性
        if(id==null || id==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.根据ID查询素材是否存在
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "素材不存在");
        }

        //4.修改是否收藏的字段
        WmMaterial wmMaterialDB = new WmMaterial();
        wmMaterialDB.setId(id);
        wmMaterialDB.setIsCollection(isCollection);
        updateById(wmMaterialDB);

        WmThreadLocalUtils.clear(); //清理当前线程绑定的用户数据

        //5.响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
